import { formatGMTDate, compareObject } from '../../../../assets/js/util.js'
import advance from '../advancedFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            // title
            title: "活跃分析",
            xlsxTitle: '',
            xlsxTitleQ: '',
            /* 的宽*/
            pageWidth: '100%',
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            // 选择的时间
            date: '',
            // 渠道数组
            plats: [],
            // 渠道数组
            channels: [],
            // 服务器数组
            servers: [],
            // 默认选择 在线趋势 PCU
            activeIndex: '1',
            activeMenu: 'dau',
            // 默认的一些时间范围
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            postObj: {
                dstart: '',
                dend: '',
                platform: '0',
                channel: '0',
                server: '0'
            },
            // 全服在线详细数据 表头
            tableHeader: [{
                prop: 'day',
                label: '日期',
                width: '160px'
            }, {
                prop: 'dau',
                label: 'DAU',
                width: 'auto'
            }, {
                prop: 'newUser',
                label: '新用户',
                width: 'auto'
            }, {
                prop: 'activeOldUser',
                label: '老用户',
                width: 'auto'
            }],
            // 数据切换
            dau: [],
            newUser: [],
            oldUser: [],
            tableData: [],
            tableDataAll: [],
            // 图表数据
            real: {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: ['']
                },
                grid: {
                    left: '1%',
                    right: '2%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    data: ['2017-5-29', '2017-5-30', '2017-5-31', '2017-6-1', '2017-6-2', '2017-6-3', '2017-6-4', '2017-6-5', '2017-6-6', '2017-6-7', '2017-6-8', '2017-6-9', '2017-5-29', '2017-5-30', '2017-5-31', '2017-6-1', '2017-6-2', '2017-6-3', '2017-6-4', '2017-6-5', '2017-6-6', '2017-6-7', '2017-6-8', '2017-6-9'],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'bar',
                    barWidth: '30px',
                    data: [2.0, 30, 7.0, 135.6, 25.6, 76.7, 135.6, 162.2, 80, 60.0, 135.6, 3.3, 2.0, 30, 7.0, 135.6, 25.6, 76.7, 135.6, 162.2, 80, 60.0, 135.6, 3.3],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#66cf97' },
                                    { offset: 0.5, color: '#4eb59a' },
                                    { offset: 1, color: '#349b98' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#4eb59a' },
                                    { offset: 0.7, color: '#349b98' },
                                    { offset: 1, color: '#66cf97' }
                                ]
                            )
                        }
                    },
                }]
            },
        }
    },
    methods: {
        //初始化
        _init() {
            window.addEventListener('resize', function() {
                this.realTimeDataChart.resize();
            }.bind(this))
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            if (that.postObj.platform == "0") {
                that.xlsxTitleQ = "全平台";
            } else if (that.postObj.platform == "3") {
                that.xlsxTitleQ = "安卓";
            } else if (that.postObj.platform == "2") {
                that.xlsxTitleQ = "ios";
            } else if (that.postObj.platform == "9") {
                that.xlsxTitleQ = "通用";
            }
            that.xlsxTitle = sheet + "-" + that.xlsxTitleQ + "-" + that.postObj.dstart + "到" + that.postObj.dend;
            that.downloadExl(that.tableHeader, that.tableDataAll, that.xlsxTitle, sheet);
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 时间改变 得到起始时间和结束时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                var t = val.split(' - ')
                this.postObj.dstart = t[0];
                this.postObj.dend = t[1];
                this.getData(this.postObj);
            }
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        // 页数
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.tableData = this.tableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === '4') {
                this.$refs.advance.filterShow = true;
                return
            }
            if (this.postObj['server'] === '0' && this.postObj['channel'] === '0') {
                this.postObj['server'] = '0';
                this.postObj['channel'] = '0';
                this.postObj['platform'] = key;
                this.getList('updatePlatform', `platform=${key}`);
                this.getData(this.postObj);
            } else {
                if (key === "3" || key === "2" || key === "9") {
                    this.errorFun("请修改为全渠道和全服！")
                }
            }

        },
        // 选择了渠道和服务器 默认的平台
        platDefault() {
            this.postObj['platform'] = "0";
        },
        //在线趋势 菜单变换  
        handle(key, keyPath) {
            var setColor = [];
            switch (key) {
                case '1':
                    setColor = ['#66cf97', '#4eb59a', '#349b98'];
                    this.activeMenu = 'dau';
                    this.echartsData(this[this.activeMenu]);
                    break;
                case '2':
                    setColor = ['#84ebd8', '#7fd2e2', '#7abde8'];
                    this.activeMenu = 'newUser';
                    this.echartsData(this[this.activeMenu]);
                    break;
                case '3':
                    setColor = ['#b8cff1', '#a99ce4', '#a07cdc'];
                    this.activeMenu = 'oldUser';
                    this.echartsData(this[this.activeMenu]);
                    break;
            }
            this.realTimeDataChart.setOption({
                series: [{
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: setColor[0] },
                                    { offset: 0.5, color: setColor[1] },
                                    { offset: 1, color: setColor[2] }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: setColor[2] },
                                    { offset: 0.7, color: setColor[1] },
                                    { offset: 1, color: setColor[0] }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        // DAU 新用户 老用户 切换
        /*activeChange(url) {
        	this.$http.jsonp(`${this.SRC}player/activePlayer/updateActiveType.do?activeType=${url}`).then(function(res){
        		var data = JSON.parse(res.body);
        		var d = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
        		if (parseInt(d["res"]) === 0) {
        			d.activeTrendDatas = d.activeTrendChart;
        			this.echartsData(d);
        		} else {
        			this.errorFun(d['msg']);
        		}
        	})
        },*/
        // 获取服务器list 平台list  服务器list
        getList(url, choose) {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    })
                }
            };
            this.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=${url}`, {
                params: { 'ps': choose }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data["res"]) === 0) {
                    // 后台select的数据
                    var lists = ["platformItmes", "channelItmes", "serverItmes"];
                    // 页面select名字
                    var nameLists = ["plats", "channels", "servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    this.getErrorMsg(Number(data.res))
                }
            })
        },
        // 获取数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.dataTotal = 0;
                that.loading = true;
                that.tableData = [];
                that.tableDataAll = [];
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `dstart=${data.dstart}&dend=${data.dend}&platform=${data.platform}&channel=${data.channel}&server=${data.server}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value)
                var d = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(d["res"]) === 0) {
                    that.dataTotal = d.activeTrendDatas.length;
                    that.tableDataAll = d.activeTrendDatas;
                    that.tableControl();
                    that.dau = d.activeTrendChart;
                    that.newUser = d.activeTrendChart1;
                    that.oldUser = d.activeTrendChart2;
                    that.echartsData(that[that.activeMenu]);
                } else {
                    that.errorFun(data["msg"])
                }
            })
        },
        // 改变表数据
        echartsData(d) {
            this.realLoadShow = false;
            if (d.length === 0) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['jsonStr'];
            }
            // 实时数据获取到数据渲染
            this.realTimeDataChart.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data.columnkeys
                },
                series: [{
                    name: data.names[0],
                    data: data.data[0]
                }]
            });
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.tableDataAll.sort(compareObject(column.prop, false));
            } else { //正序
                this.tableDataAll.sort(compareObject(column.prop, true));
            }
            this.tableControl();
        }
    },
    components: {
        'v-advance': advance
    },
    computed: {
        xlsx() {
            return this.title + '.xlsx'
        }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.date = [new Date(new Date().getTime() - 7 * 86400000), new Date()];
        this.postObj.dstart = formatGMTDate(new Date() - 86400000 * 7, true);
        this.postObj.dend = formatGMTDate(new Date().getTime(), true);
        // 获取到服务器 平台 渠道 list
        this.getList("initParam", "0");
        // 实时图
        this.realTimeDataChart = echarts.init(document.getElementById('realTimeData'));
        this.realTimeDataChart.setOption(this.real);
        // 请求数据
        this.getData(this.postObj);

        this._init();
    }
}